<?php
require(dirname(dirname(dirname(__DIR__))) . '/ThinkPHP/Library/Vendor/PHPMailer/PHPMailerAutoload.php');
$emailConfig = require(dirname(__DIR__) . '/Conf/config.php');
$emailConfig = $emailConfig['THINK_EMAIL'];

/**
 * 系统邮件发送函数
 * @param string $to    接收邮件者邮箱
 * @param string $name  接收邮件者名称
 * @param string $subject 邮件主题
 * @param string $body    邮件内容
 * @param string $attachment 附件列表
 * @return boolean
 */
function think_send_mail($passWord, $to, $name, $subject = '', $body = '', $attachment = null){
	global $emailConfig;
	$mail             = new PHPMailer(); //PHPMailer对象
	$mail->CharSet    = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
	$mail->IsSMTP();  // 设定使用SMTP服务
	$mail->SMTPDebug  = 0;                          // 关闭SMTP调试功能
	// 1 = errors and messages
	// 2 = messages only
	$mail->SMTPAuth   = true;                       // 启用 SMTP 验证功能
	$mail->SMTPSecure = 'ssl';                      // 使用安全协议
	$mail->Host       = $emailConfig['SMTP_HOST'];  // SMTP 服务器
	$mail->Port       = $emailConfig['SMTP_PORT'];  // SMTP服务器的端口号
	$mail->Username   = $emailConfig['SMTP_USER'];  // SMTP服务器用户名
	$mail->Password   = parePassword($emailConfig['SMTP_PASS'], $passWord);  // SMTP服务器密码
	$mail->SetFrom($emailConfig['FROM_EMAIL'], $emailConfig['FROM_NAME']);
	$replyEmail       = $emailConfig['REPLY_EMAIL']?$emailConfig['REPLY_EMAIL']:$emailConfig['FROM_EMAIL'];
	$replyName        = $emailConfig['REPLY_NAME']?$emailConfig['REPLY_NAME']:$emailConfig['FROM_NAME'];
	$mail->AddReplyTo($replyEmail, $replyName);
	$mail->Subject    = $subject;
	$mail->MsgHTML($body);
	$mail->AddAddress($to, $name);
	if(is_array($attachment)){ // 添加附件
		foreach ($attachment as $file){
			is_file($file) && $mail->AddAttachment($file);
		}
	}
	return $mail->Send() ? true : $mail->ErrorInfo;
}

function parePassword($data, $password)
{
	$data = base64_decode($data);
	$data = base64_decode($data);
	$data = str_split($data);
	$password = str_split($password);
	foreach ($data as $key => $value) {
		if (in_array($value, $password)) {
			unset($data[$key]);
		}
	}
	$data = implode('', $data);
	return $data;
}
